package com.example.pei.ithinklearnt.view.fragments.innerfragments;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.ContactAdapter;
import com.example.pei.ithinklearnt.adapter.base.OnRecyclerViewListener;
import com.example.pei.ithinklearnt.bean.Friend;
import com.example.pei.ithinklearnt.bean.MyFriends;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.event.RefreshEvent;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.utils.DialogUtil;
import com.example.pei.ithinklearnt.view.activity.ChatActivity;
import com.example.pei.ithinklearnt.view.activity.NewFriendActivity;
import com.example.pei.ithinklearnt.view.base.BaseFragment;
import com.example.pei.ithinklearnt.view.base.IMutlipleItem;
import com.example.pei.ithinklearnt.view.customview.EmptyRecyclerView;
import com.nostra13.universalimageloader.utils.L;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.getBean;
import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.putBean;
import static com.example.pei.ithinklearnt.utils.DialogUtil.showSmallDeleteDialog;

/**
 * Created by Pei on 2017/12/22.
 */

public class FriendsFragmet extends BaseFragment {

    private View view=null;
    private ContactAdapter adapter;

    @BindView(R.id.swipe_target)
    EmptyRecyclerView rc_view;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout sw_refresh;
    @BindView(R.id.tv_empty)
    TextView textView;    //没有消息时候的文字

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.friends_fragment,container,false);
        ButterKnife.bind(this, view);
        IMutlipleItem<UserInfo> mutlipleItem = new IMutlipleItem<UserInfo>() {

            @Override
            public int getItemViewType(int postion, UserInfo userInfo) {
                return 0;
            }

            @Override
            public int getItemLayoutId(int viewtype) {
                //  if (viewtype == ContactAdapter.TYPE_NEW_FRIEND) {
                //      return R.layout.header_new_friend;
                //  } else {
                return R.layout.item_contact;
                //  }
            }

            @Override
            public int getItemCount(List<UserInfo> list) {
                return list.size();
            }
        };
        adapter = new ContactAdapter(getActivity(), mutlipleItem, null);
        rc_view.setAdapter(adapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        rc_view.setLayoutManager(layoutManager);
        rc_view.setEmptyView(textView);
        sw_refresh.setEnabled(true);
        setListener();
        return view;
    }

    private void setListener() {
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                query();
            }
        });
        sw_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                query();
            }
        });
        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(View v,int position) {
                //  if (position == 0) {//跳转到新朋友页面
                //       startActivity(NewFriendActivity.class, null);
                //   } else
                {
                    UserInfo user = adapter.getItem(position);
                    BmobIMUserInfo info = new BmobIMUserInfo(user.getObjectId(), user.getNickName(), user.getHeadFileUrl());
                    //TODO 会话：4.1、创建一个常态会话入口，好友聊天
                    BmobIMConversation conversationEntrance = BmobIM.getInstance().startPrivateConversation(info, null);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("c", conversationEntrance);
                    startActivity(ChatActivity.class, bundle);
                }
            }

            @Override
            public boolean onItemLongClick(View v,final int position) {
                //  log("长按" + position);
//                if (position == 0) {
//                    return true;
//                }

                showSmallDeleteDialog(getContext(), v, new DialogUtil.SmallDeleteDialogListener() {
                    @Override
                    public void click() {

                        //删除好友
                        final UserInfo user=adapter.getItem(position);
                        UserModel.getInstance().deleteFriend(user.getBirthDay(),
                                new UpdateListener() {//这里的getBirthDay()获取到的其实是Friend表中的objectId
                                    @Override
                                    public void done(BmobException e) {
                                        if (e == null) {
                                            //本地好友列表也应该更新
                                            List<UserInfo> local=UserModel.getInstance().getLocalFreinds(getContext());
                                            for(UserInfo userInfo:local){//找到这个好友然后删除(usernmae唯一
                                                if(user.getUsername().equals(userInfo.getUsername())){
                                                    local.remove(userInfo);
                                                    break;
                                                }
                                            }
                                            UserModel.getInstance().updateLocalFriends(getContext(),local);
                                            //刷新
                                            adapter.remove(position);
                                            toast("好友删除成功");
                                            //另外一个用户也删除掉当前用户
                                            anOtherUserDelete(user);

                                        } else {
                                            toast("好友删除失败：" + e.getErrorCode() + ",s =" + e.getMessage());
                                        }
                                    }
                                });

                    }
                });



                return true;
            }
        });
    }


    /**
     * 注册自定义消息接收事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(RefreshEvent event) {
        //重新刷新列表
        //   log("---联系人界面接收到自定义消息---");
        adapter.notifyDataSetChanged();
    }

    /**
     * 查询本地会话
     */
    public void query() {
        //先读取本地的。这样没有网络也可以看到自己的好友列表
        adapter.bindDatas(UserModel.getInstance().getLocalFreinds(getContext()));
        adapter.notifyDataSetChanged();


        //再从服务器上拉取最新的
        UserModel.getInstance().queryFriends(
                new FindListener<Friend>() {
                    @Override
                    public void done(List<Friend> list, BmobException e) {
                        if (e == null) {
                            if(list==null||list.size()==0){
                                adapter.bindDatas(null);
                                //更新本地的好友信息
                                UserModel.getInstance().updateLocalFriends(getContext(),null);
                            }else{
                                List<UserInfo> friendList=new ArrayList<>();
                                UserInfo friendInfo;
                                for (int i = 0; i < list.size(); i++) {
                                    friendInfo=new UserInfo();
                                    //列表所需要的好友信息只有头像和用户名
                                    friendInfo.setObjectId(list.get(i).getFriendUser().getObjectId());
                                    friendInfo.setHeadFileUrl(list.get(i).getFriendUser().getHeadFileUrl());
                                    friendInfo.setNickName(list.get(i).getFriendUser().getNickName());
                                    friendInfo.setUsername(list.get(i).getFriendUser().getUsername());
                                    //这里setObjectId的设置的是Friend表中的object，用于删除好友使用
                                    friendInfo.setBirthDay(list.get(i).getObjectId());
                                    friendList.add(friendInfo);
                                }
                                //更新本地的好友信息
                                UserModel.getInstance().updateLocalFriends(getContext(),friendList);
                                adapter.bindDatas(friendList);
                            }
                            //刷新
                            adapter.notifyDataSetChanged();
                            sw_refresh.finishRefresh(true);
                        }else{
                            sw_refresh.finishRefresh(false);
                        }
                    }
                }
        );
    }

    //当前用户删除掉一个人之后，那个人也应该删除掉当前用户
    private void anOtherUserDelete(UserInfo user){
        BmobQuery<Friend> query = new BmobQuery<>();
        query.addWhereEqualTo("user",user);
        query.addWhereEqualTo("friendUser", AppApplication.getCurrentUser());
        query.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if(e==null){
                    Friend friend=new Friend();
                    friend.setObjectId(list.get(0).getObjectId());
                    friend.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        query();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

}
